package com.ruoyi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.*;
import com.ruoyi.dto.dahua.*;
import com.ruoyi.mapper.*;
import com.ruoyi.service.IDaHuaService;
import com.ruoyi.service.IParkingAccessKeysService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.utils.JsonUtil;
import com.ruoyi.vo.dahua.DaHuaResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 大华端Service业务层处理
 * 
 * @author dongdong
 * @date 2025-08-20
 */
@Slf4j
@Service
public class DaHuaServiceImpl implements IDaHuaService {

    @Autowired
    private IParkingAccessKeysService parkingAccessKeysService;
    @Resource
    private ParkingRecordOutMapper parkingRecordOutMapper;
    @Resource
    private ParkingRecordInMapper parkingRecordInMapper;
    @Resource
    private ParkingOrderMapper parkingOrderMapper;
    @Resource
    private ParkingRecordChargeMapper parkingRecordChargeMapper;
    @Resource
    private ParkingLaneMapper parkingLaneMapper;
    @Resource
    private ParkingInfoMapper parkingInfoMapper;
    @Autowired
    private ISysConfigService configService;

    @Override
    public DaHuaResponse regist(DaHuaRegistDto registDto) {
        log.info("{} 下级平台注册请求报文: {}", registDto.getPlatformId(), registDto);
        int res = parkingAccessKeysService.updateAccessKeysByPlatformId(registDto.getPlatformId());
        DaHuaResponse response = new DaHuaResponse();
        response.setSuccess(res==1);
        return response;
    }

    @Override
    public DaHuaResponse uploadmode(DaHuaDto daHuaDto) {
        log.info("{} 获取图片上传方式请求报文: {}", daHuaDto.getPlatformId(), daHuaDto);
        ParkingAccessKeys parkingAccessKeys = parkingAccessKeysService.getAccessKeysByPlatformId(daHuaDto.getPlatformId());
        DaHuaResponse response = new DaHuaResponse();
        JSONObject data = new JSONObject();
        if (Objects.nonNull(parkingAccessKeys)) {
            //通过系统参数获取值
            String uploadMode = configService.selectConfigByKey("uploadMode");
            data.put("uploadMode", uploadMode);
            data.put("fullPic", configService.selectConfigByKey("fullPic"));
            data.put("smallPic", configService.selectConfigByKey("smallPic"));
            data.put("carInPicFlag", configService.selectConfigByKey("carInPicFlag"));
            data.put("carOutPicFlag", configService.selectConfigByKey("carOutPicFlag"));
            if (uploadMode.equals("ALIOSS")) {
                JSONObject aliossData = new JSONObject();
                aliossData.put("securityToken", configService.selectConfigByKey("securityToken"));
                aliossData.put("accessKeyId", configService.selectConfigByKey("accessKeyId"));
                aliossData.put("accessKeySecret", configService.selectConfigByKey("accessKeySecret"));
                aliossData.put("expiration", configService.selectConfigByKey("expiration"));
                aliossData.put("filePath", configService.selectConfigByKey("filePath"));
                aliossData.put("bucketName", configService.selectConfigByKey("bucketName"));
                aliossData.put("endpoint", configService.selectConfigByKey("endpoint"));
                data.put("alioss", aliossData);
            }
            response.setSuccess(true);
            response.setData(data);
        }else {
            response.setSuccess(false);
            response.setErrMsg("无效的platformId");
        }
        log.info("{} 获取图片上传方式应答报文: {}", daHuaDto.getPlatformId(), response);
        return response;
    }

    @Override
    public DaHuaResponse cancel(DaHuaDto daHuaDto) {
        log.info("{} 关闭云使能请求报文: {}", daHuaDto.getPlatformId(), daHuaDto);
        return DaHuaResponse.success(true);
    }

    @Override
    public DaHuaResponse address(DaHuaDto daHuaDto) {
        log.info("{} 获取地址请求报文: {}", daHuaDto.getPlatformId(), daHuaDto);
        ParkingAccessKeys parkingAccessKeys = parkingAccessKeysService.getAccessKeysByPlatformId(daHuaDto.getPlatformId());
        DaHuaResponse response = new DaHuaResponse();
        if (Objects.nonNull(parkingAccessKeys)) {
            JSONObject data = new JSONObject();
            data.put("url", parkingAccessKeys.getWssUrl());
            response.setSuccess(true);
            response.setData(data);
        }else {
            response.setSuccess(false);
            response.setErrMsg("无效的platformId");
        }
        log.info("{} 获取地址应答报文: {}", daHuaDto.getPlatformId(), parkingAccessKeys);
        return response;
    }

    @Override
    public DaHuaResponse carIn(DaHuaCarIEDto daHuaCarIEDto) {
        log.info("{} 上报的入场信息请求报文: {}", daHuaCarIEDto.getPlatformId(), daHuaCarIEDto);
        // 过滤重复数据
        CopyOptions copyOptions = CopyOptions.create().ignoreError().setIgnoreProperties("carInTime");
        ParkingRecordIn parkingRecordIn = new ParkingRecordIn();
        BeanUtil.copyProperties(daHuaCarIEDto, parkingRecordIn, copyOptions);
        parkingRecordIn.setCarInTime(DateUtils.strToLocalDateTime(daHuaCarIEDto.getCarInTime()));
        List<ParkingRecordIn> list = parkingRecordInMapper.selectParkingRecordInByCarNumTimeChnCode(parkingRecordIn);
        if (list.isEmpty()){
            ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoByParkCode(daHuaCarIEDto.getPlatformId(), daHuaCarIEDto.getParkingLotCode());
            parkingRecordIn.setEnterItcDevChnName(daHuaCarIEDto.getEnterItcDevChnname());
            parkingRecordIn.setDeptId(parkingInfo.getDeptId());
            parkingRecordInMapper.insertParkingRecordIn(parkingRecordIn);
        }
        return DaHuaResponse.success(true);
    }

    @Override
    public DaHuaResponse carOut(DaHuaCarIEDto daHuaCarIEDto) {
        log.info("{} 上报的出场信息请求报文: {}", daHuaCarIEDto.getPlatformId(), daHuaCarIEDto.getCarNum());
        CopyOptions copyOptions = CopyOptions.create().ignoreError().setIgnoreProperties("carOutTime");
        ParkingRecordOut parkingRecordOut = new ParkingRecordOut();
        BeanUtil.copyProperties(daHuaCarIEDto, parkingRecordOut, copyOptions);
        parkingRecordOut.setCarOutTime(DateUtils.strToLocalDateTime(daHuaCarIEDto.getCarOutTime()));
        List<ParkingRecordOut> list = parkingRecordOutMapper.selectParkingRecordOutByCarNumTimeChnCode(parkingRecordOut);
        if (list.isEmpty()){
            ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoByParkCode(daHuaCarIEDto.getPlatformId(), daHuaCarIEDto.getParkingLotCode());
            parkingRecordOut.setExitItcDevChnName(daHuaCarIEDto.getExitItcDevChnname());
            parkingRecordOut.setDeptId(parkingInfo.getDeptId());
            parkingRecordOutMapper.insertParkingRecordOut(parkingRecordOut);
        }
        return DaHuaResponse.success(true);
    }

    @Override
    public DaHuaResponse chargeRecord(DaHuaChargeDto daHuaChargeDto) {
        log.info("{} 上报收费记录请求报文: {}", daHuaChargeDto.getPlatformId(), daHuaChargeDto);
        parkingOrderMapper.updateOrderStatusByOrderNo(4, daHuaChargeDto.getSerialNumber());
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoByParkCode(daHuaChargeDto.getPlatformId(), daHuaChargeDto.getParkingLotCode());
        CopyOptions copyOptions = CopyOptions.create().ignoreError().setIgnoreProperties("carInTime", "carOutTime");
        ParkingRecordCharge parkingRecordCharge = new ParkingRecordCharge();
        BeanUtil.copyProperties(daHuaChargeDto, parkingRecordCharge, copyOptions);
        parkingRecordCharge.setCarInTime(DateUtils.strToLocalDateTime(daHuaChargeDto.getCarInTime()));
        parkingRecordCharge.setCarOutTime(DateUtils.strToLocalDateTime(daHuaChargeDto.getCarOutTime()));
        parkingRecordCharge.setDeptId(parkingInfo.getDeptId());
        parkingRecordChargeMapper.insertParkingRecordCharge(parkingRecordCharge);
        return DaHuaResponse.success(true);
    }

    @Override
    public DaHuaResponse sync(DaHuaSyncLaneDto daHuaSyncLaneDto) {
        log.info("{} 上报车道信息同步请求报文: {}", daHuaSyncLaneDto.getPlatformId(), daHuaSyncLaneDto);
        List<DaHuaLaneDto> lanes = JsonUtil.jsonToList(daHuaSyncLaneDto.getLanes(), DaHuaLaneDto.class);
        Date date = DateUtils.getNowDate();
        for (DaHuaLaneDto lane : lanes) {
            ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoByParkCode(daHuaSyncLaneDto.getPlatformId(), daHuaSyncLaneDto.getParkingLotCode());
            if(Objects.nonNull(parkingInfo)){
                Long parkId = parkingInfo.getId();
                ParkingLane parkingLane = parkingLaneMapper.selectParkingLaneByParkIdAndLane(parkId, lane.getLaneCode());
                if(Objects.isNull(parkingLane)){
                    parkingLane = new ParkingLane();
                    setParkingLaneProperties(parkingLane, lane, parkingInfo);
                    parkingLane.setCreateTime(date);
                    parkingLaneMapper.insertParkingLane(parkingLane);
                }else {
                    setParkingLaneProperties(parkingLane, lane, parkingInfo);
                    parkingLane.setUpdateTime(date);
                    parkingLaneMapper.updateParkingLane(parkingLane);
                }
            }
        }
        return DaHuaResponse.success(true);
    }

    @Override
    public DaHuaResponse lotReport(DaHuaLotReportDto daHuaLotReportDto) {
        log.info("{} 上报场区余位请求报文: {}", daHuaLotReportDto.getPlatformId(), daHuaLotReportDto);
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoByParkCode(daHuaLotReportDto.getPlatformId(), daHuaLotReportDto.getParkingLotCode());
        if(Objects.nonNull(parkingInfo)){
            parkingInfo.setTotalLot(daHuaLotReportDto.getTotalLot());
            parkingInfo.setIdleLot(daHuaLotReportDto.getIdleLot());
            parkingInfo.setMonthTotalLot(daHuaLotReportDto.getMonthTotalLot());
            parkingInfo.setMonthIdleLot(daHuaLotReportDto.getMonthIdleLot());
            parkingInfoMapper.updateParkingInfo(parkingInfo);
        }
        return DaHuaResponse.success(true);
    }

    // 设置车道属性的通用方法
    private void setParkingLaneProperties(ParkingLane parkingLane, DaHuaLaneDto lane, ParkingInfo parkingInfo) {
        parkingLane.setLaneCode(lane.getLaneCode());
        parkingLane.setLaneName(lane.getLaneName());
        parkingLane.setLaneDirect(lane.getLaneDirect());
        parkingLane.setQrCodeId(lane.getQrCodeId());
        parkingLane.setParkId(parkingInfo.getId());
        parkingLane.setDeptId(parkingInfo.getDeptId());
    }
}
